package finger.service.impl;

import finger.dao.BookDao;
import finger.dao.impl.BookDaoImpl;
import finger.domain.Book;
import finger.domain.Page;
import finger.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {
    BookDao dao = new BookDaoImpl();

    @Override
    public int addBook(Book book) {
        return dao.addBook(book);
    }

    @Override
    public int deleteBookById(Integer id) {
        return dao.deleteBook(id);
    }

    @Override
    public int updateBook(Book book) {
        return dao.updateBook(book);
    }

    @Override
    public Book queryBookById(Integer id) {
        return dao.queryBookById(id);
    }

    @Override
    public List<Book> queryBooks() {
        return dao.queryBooks();
    }

    @Override
    public Page<Book> page(int pageNo, int pageSize) {
        Page<Book> page = new Page<>();

        page.setPageSize(pageSize);
        Integer pageTotalCount = dao.queryPageTotalCount();
        page.setPageTotalCount(pageTotalCount);
        Integer pageTotal = (pageTotalCount / pageSize);
        if (pageTotalCount % pageSize > 0) {
            pageTotal++;
        }
        page.setPageTotal(pageTotal);
        page.setPageNo(pageNo);
        int begin = (page.getPageNo()-1)*pageSize;
        List<Book> books = dao.queryForItems(begin,pageSize);
        page.setItems(books);
        return page;
    }

    @Override
    public Page pageByPrice(Integer pageNo, Integer pageSize, Integer min, Integer max) {
        Page page = new Page();
        page.setPageSize(pageSize);
        Integer pageTotalCount = dao.queryPageTotalCountByPrice(min, max);
        page.setPageTotalCount(pageTotalCount);
        Integer pageTotal = (pageTotalCount/pageSize);
        if(pageTotalCount%pageSize>0){
            pageTotal++;
        }
        page.setPageTotal(pageTotal);
        page.setPageNo(pageNo);
        Integer begin = (pageNo-1)*pageSize;
        List<Book> books = dao.queryForItemsByPrice(begin,pageSize, min, max);
        page.setItems(books);
        return page;
    }
}
